//
//  HJWebSocketResponseManager.m
//  KaiChat
//
//  Created by lx on 2023/10/24.
//

#import "HJWebSocketResponseManager.h"
#import "HJWebSocketManager.h"
#import "HJChatMessageModel.h"
#import "HJDataPacketHeader.h"
#import "HJChatSessionModel.h"
#import "HJChatGroupModel.h"
#import "HJIM.h"

@interface HJWebSocketResponseManager()<HJWebSocketManagerDelegate>


@end


static HJWebSocketResponseManager *_webSocketResponseManager = nil;

@implementation HJWebSocketResponseManager

+ (instancetype)shareManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _webSocketResponseManager = [[self alloc] init];
        [[HJWebSocketManager shareManager] addDelegate:_webSocketResponseManager];
    });
    return _webSocketResponseManager;
    
}

+ (void)load {
    [HJWebSocketResponseManager shareManager];
}

- (void)webSocket:(HJWebSocketManager *)webSocketManager didReceiveMessage:(NSDictionary *)message {
    
    NSInteger chatType = [message[@"op"] intValue];
    NSNumber *serverMsgId = message[@"seq_id"];
    
    if (chatType == HJChatTypeSingle || chatType == HJChatTypeGroup) {
        [self comfirmMessageWithMessageId:serverMsgId];
    }

    dispatch_async_serial_queue(^{
        
        HJChatMessageModel *messageModel = [HJChatMessageModel messageModelWithDict:message];
       
        
        if (chatType == HJChatTypeSingle) {
            [HJIM.shareIM.userManager queryFriendInfoWithUserId:messageModel.senderId complete:^(HJChatFriendModel * _Nullable friendModel) {
                
                if (!friendModel) return;
                
                messageModel.senderAvatar = friendModel.avatar;
                messageModel.senderNickname = friendModel.showName;
                messageModel.receiverAvatar = HJUserInfo.avatar;
                messageModel.receiverNickname = HJUserInfo.nickname;
                
                [self addConversationWithMessageModel:messageModel];
            }];
            return;
        }
        
        if (chatType == HJChatTypeGroup) {
            
            [HJIM.shareIM.groupManager queryGroupInfoByGroupId:messageModel.groupId completion:^(HJChatGroupModel * _Nullable groupModel) {
                
                if (!groupModel) return;
                
                messageModel.sessionAvatar = groupModel.avatar;
                messageModel.sessionName = groupModel.name;
                
                [self addConversationWithMessageModel:messageModel];
                
            }];
            return;
        }
    });
    
}

- (void)addConversationWithMessageModel:(HJChatMessageModel *)messageModel {
    
    BOOL isNewMessage = [HJIM.shareIM.messageManager queryMessageBySessionId:messageModel.sessionId messageId:messageModel.msgId] == nil;
    
    HJChatSessionModel *sessionModel = [HJChatSessionModel sessionModelWithMessageModel:messageModel];
    sessionModel.isSendMsg = @"2";
    if (isNewMessage) {
        if (![messageModel isTipMessage]) {
            sessionModel.unReadCount = @"1";
            sessionModel.muteMessageUnReadCount = @"0";
        }
    }
    
    [HJIM.shareIM.conversationManager addConversation:sessionModel];
    [messageModel downloadVoice];
    if (isNewMessage) {
        [messageModel bg_save];
        [[NSNotificationCenter defaultCenter] postNotificationName:receiveNewMessageNotification object:messageModel];
    } else {
        [messageModel bg_saveOrUpdate];
    }
}

- (void)comfirmMessageWithMessageId:(NSNumber *)messageId {
    NSDictionary *dict = @{
        @"seq_id": messageId,
    };
    NSData *bodyData = dict.mj_JSONData;
    HJDataPacketHeader *packetHeader = [[HJDataPacketHeader alloc] initWithBodyData:bodyData seq:messageId.intValue operation:20];
    NSData *packetData = HJMakePacketData(packetHeader.data, bodyData);
    [[HJWebSocketManager shareManager] sendData:packetData error:nil];
}


- (void)webSocket:(HJWebSocketManager *)webSocketManager didConnectFail:(NSError *)error {
    
    
}

- (void)dealloc {
    [[HJWebSocketManager shareManager] removeDelegate:self];
}

//                        if (sessionModel.disturb.boolValue) {
//                            sessionModel.unReadCount = @"0";
//                            sessionModel.muteMessageUnReadCount = @"1";
//                        } else {
//                            sessionModel.unReadCount = @"1";
//                            sessionModel.muteMessageUnReadCount = @"0";
//                        }

@end
